let util = {};
util.title = function (title) {
  title = title || '中车石家庄MES智造系统';
  window.document.title = title;
};

util.inOf = function (arr, targetArr) {
  let res = true;
  arr.forEach(item => {
    if (targetArr.indexOf(item) < 0) {
      res = false;
    }
  });
  return res;
};

util.oneOf = function (ele, targetArr) {
  if (targetArr.indexOf(ele) >= 0) {
    return true;
  } else {
    return false;
  }
};

util.contains = function (targetArr, ele) {
  let i = targetArr.length;
  while (i--) {
    if (targetArr[i] === ele) {
      return true;
    }
  }
  return false;
};

util.showThisRoute = function (itAccess, currentAccess) {
  if (itAccess) {
    return currentAccess.some(role => itAccess.indexOf(role) >= 0);
  } else {
    return true;
  }
};
util.getRouterObjByName = function (routers, name) {
  if (!name || !routers || !routers.length) {
    return null;
  }
  // debugger;
  let routerObj = null;
  for (let item of routers) {
    if (item.name === name) {
      return item;
    }
    routerObj = util.getRouterObjByName(item.children, name);
    if (routerObj) {
      return routerObj;
    }
  }
  return null;
};
util.getDefaultColumn = function (params) {
  let index = 'home_index';
  try {
    params.forEach(role => {
      let columns = role.authIds;
      if (columns !== undefined && columns !== null && columns instanceof Array) {
        if (columns.length > 0) {
          let column = columns[0];
          index = column;
        }
      }
    });
  } catch (err) {
    //
  }
  return index;
};
util.handleTitle = function (vm, item) {
  if (typeof item.title === 'object') {
    return vm.$t(item.title.i18n);
  } else {
    return item.title;
  }
};
util.loopCheckName = function (vm, item, name, checkData) {
  if (item.name === name) {
    let title = util.handleTitle(vm, item);
    checkData.title = title;
    if (item.name === 'otherRouter') {
      checkData.isOtherRouter = true;
    }
  }

  if (item.children !== undefined && item.children.length > 0) {
    item.children.forEach(child => {
      util.loopCheckName(vm, child, name, checkData);
    });
  }
};
util.oneOfRouters = function (ele, targetArr) {
  let obj = targetArr.filter(item => {
    if (ele.name === item.name) {
      return true;
    }
    return false;
  });
  return obj.length > 0;
};
util.loopCheckRouters = function (vm, list, name) {
  let checklist = [];
  list.forEach(child => {
    if (child.name === name) {
      if (!util.oneOfRouters(child, checklist) && child.name !== 'otherRouter') {
        checklist.push(child);
      }
      return checklist;
    }
    if (child.children !== undefined) {
      let subchecklist = util.loopCheckRouters(vm, child.children, name);
      subchecklist.forEach(child => {
        if (!util.oneOfRouters(child, checklist) && child.name !== 'otherRouter') {
          checklist.push(child);
        }
      });
      if (subchecklist.length > 0) {
        if (!util.oneOfRouters(child, checklist) && child.name !== 'otherRouter') {
          checklist.push(child);
        }
        return checklist;
      }
    }
  });

  return checklist;
};
util.unshiftArray = function (list) {
  let currentPathArray = [];
  list.forEach(item => {
    currentPathArray.unshift({
      title: item.title,
      path: item.path,
      children: item.children,
      redirect: item.redirect,
      icon: item.icon,
      name: item.name
    });
  });
  return currentPathArray;
};
util.compareSameIndexData = function (list1, list2, index) {
  if (list1.length <= index || list2.length <= index) {
    return false;
  }
  return list1[index].name === list2[index].name;
};
util.obtainItem = function (list, item) {
  if (item.path === 'index') {
    return;
  }

  list.push({
    title: item.title,
    path: item.path,
    children: item.children,
    redirect: item.redirect,
    icon: item.icon,
    name: item.name,
    params: item.params,
    query: item.query
  });
};

util.checkListFinished = function (list) {
  if (list.length === 0) {
    return true;
  }

  //  需要忽略掉所有 path index 路由
  if (list.length === 1) {
    return list[0].path === 'index';
  }
  return false;
};
util.setCurrentPath = function (vm, myroute) {
  let currentPathHis = vm.$store.state.app.currentPath;
  let routers = vm.$store.state.app.routers;
  // console.log('currentPathHis', currentPathHis);

  let currentPathArray = [...currentPathHis];

  // currentPathArray.forEach(item => {
  //   console.log('写入数据：' + item.name);
  // });
  currentPathArray.shift();
  let routerlist = util.loopCheckRouters(vm, routers, myroute.name);
  let _routerlist = util.unshiftArray(routerlist);
  // console.log('routerlist', _routerlist);

  // currentPathArray 为历史面包屑
  // routerlist 为新面包屑

  // 对比前两级或者前N级，如果相同，则后续比对，如果出现不一样的情况，直接使用新路由规则

  let compareResultOnlyUseNew = false;
  // 暂时定位对比2级
  let compareLevel = 2;

  for (let level = 0; level < compareLevel; level++) {
    if (util.compareSameIndexData(currentPathArray, _routerlist, level)) {
      // 相同级栏目
    } else {
      compareResultOnlyUseNew = true;
      break;
    }
  }

  // TODO 需要添加算法，用于随意累加面包屑，需要再路由定义上添加  nail  参数，定义为ture 的规则需要变化一二级路由，否则是累加规则

  let showCurrentPathArray = [{
    title: '首页',
    path: '/home',
    icon: 'ios-home',
    name: 'home_index'
  }];

  if (compareResultOnlyUseNew) {
    // 很简单，只需要使用新的路由就行了
    // console.log('所有数据使用新路由数据');

    //    写入 showCurrentPathArray  数据

    while (_routerlist.length > 0) {
      let item = _routerlist.shift();
      // console.log('写入数据：' + item.name);

      util.obtainItem(showCurrentPathArray, item);
    }
  } else {
    // 循环处理历史路由
    // console.log('循环处理历史路由');
    while (true) {
      let item = currentPathArray.shift();
      if (_routerlist.length > 0 && _routerlist[0].name === item.name) {
        // 发现出现相同的情况， 则 拿出数据，对比生成新数据，并且
        let newItem = _routerlist.shift();
        //    写入 showCurrentPathArray  数据

        let _item = util.compareObtainTwoRoute(item, newItem);

        // console.log('写入相同数据：' + item.name);
        // console.log('写入相同数据1 path：', item.path);
        // console.log('写入相同数据2 path：', new_item.path);
        // console.log('写入相同数据1 params：', item.params);
        // console.log('写入相同数据2 params：', new_item.params);
        // console.log('写入相同数据1 query：', item.query);
        // console.log('写入相同数据2 query：', new_item.query);

        util.obtainItem(showCurrentPathArray, _item);

        if (util.checkListFinished(_routerlist)) {
          // 已经执行到新的路由终点，结束
          break;
        }
      } else {
        //    写入 showCurrentPathArray  数据

        // console.log('写入历史不相同数据：' + item.name);
        // console.log('写入历史不相同数据1 path：', item.path);
        // console.log('写入历史不相同数据2 params：', item.params);
        // console.log('写入历史不相同数据3 query：', item.query);

        util.obtainItem(showCurrentPathArray, item);
      }
      if (currentPathArray.length === 0) {
        // 已经执行到历史路由终点，结束
        break;
      }
    }

    // console.log('循环处理新路由');
    // 循环处理新路由
    while (_routerlist.length > 0) {
      let item = _routerlist.shift();
      //    写入 showCurrentPathArray  数据

      if (item.name === myroute.name) {
        item = util.compareObtainTwoRoute(myroute, item);
      }

      // console.log('写入数据：' + item.name);
      // console.log('写入数据1 path：', item.path);
      // console.log('写入数据2 params：', item.params);
      // console.log('写入数据3 query：', item.query);

      util.obtainItem(showCurrentPathArray, item);
    }
  }

  vm.$store.commit('updateSecondLevelMenulist', {menu: showCurrentPathArray[1], route: myroute});
  vm.$store.commit('setCurrentPath', showCurrentPathArray);

  return showCurrentPathArray;
};
util.checkMenuRole = function (menu, roles) {
  if (roles.indexOf(menu.name) >= 0) {
    return true;
  }
  if (menu.children !== undefined) {
    for (let index = 0; index < menu.children.length; index++) {
      let submenu = menu.children[index];
      if (util.checkMenuRole(submenu, roles)) {
        return true;
      }
    }
  }
  return false;
};
util.removeList = function (list) {
  let _list = [];
  for (let i = 0; i < list.length - 1; i++) {
    _list.push(list[i]);
  }
  return _list;
};
util.validateErrorPage = function (route) {
  return route.name === '404' || route.name === '500' || route.name === '403' || route.name === 'error-404';
};
util.validateOtherPage = function (route) {
  return route.name === 'otherRouter' || route.name === 'home_index';
};
util.compareObtainTwoRoute = function (_new, old) {
  return {
    fullPath: old.fullPath === undefined ? _new.fullPath : old.fullPath,
    matched: old.matched === undefined ? _new.matched : old.matched,
    path: old.path === undefined ? _new.path : old.path,
    name: old.name === undefined ? _new.name : old.name,
    title: old.title === undefined ? _new.title : old.title,
    icon: old.icon === undefined ? _new.icon : old.icon,

    meta: old.meta === undefined ? _new.meta : old.meta,
    params: old.params === undefined ? _new.params : old.params,
    query: old.query === undefined ? _new.query : old.query,
    children: old.children === undefined ? _new.children : old.children,
    redirect: old.redirect === undefined ? _new.redirect : old.redirect

  };
};
util.openNewPage = function (vm, name, argu, query) {
  let pageOpenedList = vm.$store.state.app.pageOpenedList;
  let openedPageLen = pageOpenedList.length;
  let i = 0;
  while (i < openedPageLen) {
    if (name === pageOpenedList[i].name) { // 页面已经打开
      vm.$store.commit('pageOpenedList', {
        index: i,
        argu: argu,
        query: query
      });
      break;
    }
    i++;
  }
  vm.$store.commit('setCurrentPageName', name);
};

util.toDefaultPage = function (routers, name, route, next) {
  let len = routers.length;
  let i = 0;
  let notHandle = true;
  while (i < len) {
    if (routers[i].name === name && routers[i].children && routers[i].redirect === undefined) {
      route.replace({
        name: routers[i].children[0].name
      });
      notHandle = false;
      next();
      break;
    }
    i++;
  }
  if (notHandle) {
    next();
  }
};

util.fullscreenEvent = function (vm) {
  vm.$store.commit('initCachepage');
  // 权限菜单过滤相关
  vm.$store.commit('updateMenulist');
  // 全屏相关
};
util.findFirstLevelActiveRoute = function (vm) {
  let currentPath = vm.$store.state.app.currentPath;
  // if (currentPath.length >= 2) {
  //   return currentPath[2];
  // }
  if (currentPath.length >= 1) {
    return currentPath[1];
  }
  return null;
};
util.findSecondLevelActiveRoute = function (vm) {
  let currentPath = vm.$store.state.app.currentPath;
  if (currentPath.length >= 2) {
    return currentPath[2];
  }
  return null;
};

util.findFirstLevelSwitchRoute = function (vm, name) {
  let routers = vm.$store.state.app.routers;
  let obj = routers.filter(item => {
    if (item.name === name) {
      return item;
    }
  });
  return obj.length > 0 ? obj[0] : {};
};

util.findSecondLevelActiveRouteWithPath = function(vm, path) {
  let routers = vm.$store.state.app.routers;
  console.log("routers", routers)
  console.log("routers.length", routers.length)
  for (let index = 0; index < routers.length; index++) {
    let submenu = routers[index];

    console.log("submenu", submenu)

    for (let sindex = 0; sindex < submenu.children.length; sindex++) {
      let submenu2 = submenu.children[sindex];
      if (util.checkMenuPath(submenu2, path)) {
        return submenu2.name;
      }
    }
  }
  return path;
};
util.checkMenuPath = function(submenu, path) {
  if (submenu.name === path) {
    console.log("submenu22222", submenu)
    return true;
  }
  if (submenu.children !== undefined) {
    for (let index = 0; index < submenu.children.length; index++) {
      let submenu2 = submenu.children[index];
      if (util.checkMenuPath(submenu2, path)) {
        return true;
      }
    }
  }
  return false;
};

// util.checkUpdate = function (vm) {
//     axios.get('https://api.github.com/repos/iview/iview-admin/releases/latest').then(res => {
//         let version = res.data.tag_name;
//         vm.$Notice.config({
//             duration: 0
//         });
//         if (semver.lt(packjson.version, version)) {
//             vm.$Notice.info({
//                 title: 'iview-admin更新啦',
//                 desc: '<p>iView-admin更新到了' + version + '了，去看看有哪些变化吧</p><a style="font-size:13px;" href="https://github.com/iview/iview-admin/releases" target="_blank">前往github查看</a>'
//             });
//         }
//     });
// };

util.getNodeKey = function (node) {
  try {
    return node.getNodeKey();
  } catch (e) {
    return undefined;
  }
};

export default util;
